﻿using System.Linq;
using CcrFlows.Internal.Stages;
using Microsoft.Ccr.Core;
using NUnit.Framework;

namespace Test.CcrFlows
{
    [TestFixture]
    public class testJoinStage
    {
        [Test]
        public void Create_join()
        {
            StageBase join = new JoinStage<int, string, string>((i,s, ps) => ps.Post(i + s));

            join.Input.ElementAt(0).Post(99);
            join.Input.ElementAt(1).Post("x");

            string t;
            Assert.IsTrue(((Port<string>)join.Output.First()).WaitFor(500, out t));
            Assert.AreEqual("99x", t);
        }


        [Test]
        public void Append_simpleStage_to_join()
        {
            StageBase join = new JoinStage<int, string, string>((i, s, ps) => ps.Post(i + s));
            StageBase simple = new SeqStage<string, string>((s, ps) => ps.Post(s + "y"));
            join.ContinueWith(0, simple);

            join.Input.ElementAt(0).Post(99);
            join.Input.ElementAt(1).Post("x");

            string t;
            Assert.IsTrue(((Port<string>)simple.Output.First()).WaitFor(500, out t));
            Assert.AreEqual("99xy", t);
        }

        [Test]
        public void Append_join_to_branches()
        {
            StageBase b0 = new SeqStage<int, int>((i, pi) => pi.Post(i + 1));
            StageBase b1 = new SeqStage<string, string>((s, ps) => ps.Post(s + "x"));
            StageBase j = new JoinStage<int, string, string>((i, s, ps) => ps.Post(i + "/" + s));

            b0.ContinueWith(0, j, 0);
            b1.ContinueWith(0, j, 1);

            b0.Input.ElementAt(0).Post(99);
            b1.Input.ElementAt(0).Post("hello");

            string t;
            Assert.IsTrue(((Port<string>) j.Output.First()).WaitFor(500, out t));
            Assert.AreEqual("100/hellox", t);
        }
    }
}
